package com.example.day06;


import com.example.constract.UserStatus;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author jeff
 */
public class UserStatusEnumsTypeHandler extends BaseTypeHandler<UserStatus> {

    public UserStatusEnumsTypeHandler(){
    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, UserStatus parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("正在设置PreparedStatement参数："+parameter+"，value："+parameter.getValue());
        ps.setInt(i, parameter.getValue());
    }

    UserStatus getValue(int value) {
        System.out.println("正在转换结果集数据："+value);
        UserStatus[] values = UserStatus.values();
        for (UserStatus userStatus : values) {
            if (value==userStatus.getValue()){
                System.out.println("已匹配到数据："+userStatus);
                return userStatus;
            }
        }
//        TODO 如果找不到数据，是否抛出异常？或者是否要给个异常值？
        System.out.println("未获取到正确数据，需要检查数据库内容");
        return null;
    }

    @Override
    public UserStatus getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i =rs.getInt(columnName);
        if (0==i && rs.wasNull()) return null;
        return getValue(i);
    }

    @Override
    public UserStatus getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i =rs.getInt(columnIndex);
        if (0==i && rs.wasNull()) return null;
        return getValue(i);
    }

    @Override
    public UserStatus getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i =cs.getInt(columnIndex);
        if (0==i && cs.wasNull()) return null;
        return getValue(i);
    }
}
